<template>
	<view style="padding-bottom: 10px;">
		
		<u-empty    v-if="list.length==0&status!='loadmore'"   text="当前无服务长者信息"    icon="https://cdn.uviewui.com/uview/empty/history.png">
		</u-empty>
		<view v-else class="box" v-for="(item, index) in list">
			<u-row customStyle="margin-bottom: 10px">
			   <u-col span="5">
				   <view>
						<image mode="aspectFill" :src="item.src||src"></image>
				   </view>
			   </u-col>
			   <u-col span="7">
			       <view class="xinxi">
					   <p>姓名：<span style="font-size: 40rpx;">{{item.elderlyName||""}}</span> </p>
					   <p>性別：<span>{{item.sex||calculateAgeAndGender(item.idCard,"sex")}}</span></p>
					   <p>年龄：<span>{{item.age||calculateAgeAndGender(item.idCard,"age")}}</span></p>
					   <p>电话：<span>{{item.contactsPhone||"无"}}</span></p>
					    <p>完成单数：<span>{{item.Nnumber||"0"}}单</span></p>
						              
						
				   </view>
			   </u-col>
			  
			</u-row>
			<view class="address">
					地址：{{item.address||"无 "}}
			</view>
			<view class="" >
				<u-row customStyle="margin-bottom: 10px">
					<u-col span="2">
						<view >
							<u-button icon="phone" plain
							    type="primary" shape="circle"size="small" text="联系" @click="getPhoneNumber(item.contactsPhone)"
								  color="linear-gradient(to right, rgb(254, 223, 77), rgb(255, 211, 77))"
							></u-button>
						</view>
					</u-col>
					<u-col span="2">
						<view >
							<u-button  plain
							    type="primary" shape="circle"size="small" text="查单" @click="navigateToAuditCompletedOrde(item)"
								  color="linear-gradient(to right, rgb(254, 223, 77), rgb(255, 211, 77))"
							></u-button>
						</view>
					</u-col>
					<u-col span="8">
						<view class="btn2" style="margin-left: 10px;">
							<u-button type="primary" shape="circle"size="small" text="添加服务单" @click="clickService(item)"
								 color="linear-gradient(to right, rgb(0, 202, 91), rgb(0, 172, 78))"
							></u-button>
						</view>
					</u-col>
				</u-row>
				
			</view>
		</view>
		<!-- 服务内容弹窗  -->
		<u-popup :show="showService"  :round="10" mode="center" @close="close" @open="open"  closeable>
            <view class="service"><!--  -->
			<br/>
				<uni-list>
					<uni-list-item :class="{'actives':from.serveName!='请选择服务'}" showArrow title="服务项目:" :rightText="from.serveName" clickable  @click="showSearchPicker=true" />
					
				</uni-list>
				<view class="buttonSER">
					<u-button  type="primary" shape="circle"size="small" text="确认服务" @click="clickStartService()"
						 color="linear-gradient(to right, rgb(254, 223, 77), rgb(255, 211, 77))"
					></u-button>
				</view>
				
                <search-picker
                	v-model="showSearchPicker"
                	title="请选择服务"
                	:data="datalist"
                	:initSelected="initSelected"
                	:showSearch="true"
                	:multiple="false"
                	@confirm="onConfirm"
                	
                />
            </view>
		</u-popup>
		
	</view>
</template>

<script>
	import {
	    mapState 
	} from 'vuex';
	export default {
		data() {
			return {
				src: 'https://cdn.uviewui.com/uview/album/1.jpg',
				status: 'loadmore',//上滑加载函数
				key:0,
				list:[],
				initSelected: [],
				showService:false,
				ederly:{},
				from:{
					serveName:"请选择服务",
					price:"",
					unit:"",
					id:"",
				},
				datalist:[
					{
						label:'单元2',
						value:1
					},
					{
						label:'单元1',
						value:2
					}
				],
				showSearchPicker:false,
				pageVO:{
					pageNo: 1,
					pageSize: 5,
					technicianId:"",
					state:"服务中"
				},
				
			}
		},
		computed: {
			//获取是否登录
			...mapState(['userInfo']) 
		},
		mounted() {
			//获取当前位置 需用户授权  
			this.showPage(true)
		},
		methods: {
			//完成数量查询
			serviceNumber(row,index){
				let data={
					userPhone:row.contactsPhone,
					userName:row.elderlyName,
					pageNo: 1,
					pageSize: 5,
					orderStatus:"4,9",
					technicianId:row.technicianId,
					projectId:row.projectId
				}
				console.log("查询："+JSON.stringify(data))
				//获
				this.request.getRequest(this.http.httpsLian.homemakingOrder,data, true)
				.then(res => { 
					let data=this.list
					data[index].Nnumber=res.data.total
					this.list=[]
					this.list=data
					//console.log("下标："+index)
					//console.log("完成数量查询："+index+JSON.stringify(this.list[index].Nnumber))
					
				}).catch(res => {
				})
				
			},
			//获取数据
			showPage(type){
				let this_=this
				this.pageVO.technicianId=this.userInfo.id
				this.request.getRequest(this.http.httpsLian.homemakingProjectElderly,this.pageVO, type)
				.then(res => { 
					//console.log("获取数据2：",res.data)
					if(res.code!=0 )return
					if(res.data.length==0) {
					    this.status = 'nomore';
					    return
					}
					this.list=res.data
					res.data.forEach((item,index)=>{
						console.log("indexindex",index)
						this_.serviceNumber(item,index)
					})
					
					
				}).catch(res => {
					uni.$u.toast(res)
				})
			},
			navigateTodetails(itme){
				 let data={
				 	list:this.datalist,
					elderly:itme,
				 }
				uni.navigateTo({
				   url: "/pages/elderly/startService?params="+encodeURIComponent(JSON.stringify(itme))
				                                              
				});
			},
			//提交开始服务
			clickStartService(){
				
				if(this.from.serveName=="请选择服务"){
					uni.showToast({
						title:"请选择服务",
						icon:"none",
					})
					return
				}
				console.log("登陆信息",this.userInfo)
				console.log("老人信息",this.ederly)
				console.log("选择的服务",this.from)
				
				//订单信息组合
				let orde={
					userId: this.ederly.elderlyId,
					userName:this.ederly.elderlyName,
					userPhone:this.ederly.contactsPhone,
					userAddress:this.ederly.address,
					
					appointmentPrice:this.from.price,
					totalPrice:this.from.price,
					serveId:this.from.id,
					serveName:this.from.serveName,
					serviceCount:1,
					appointmentTime:this.utils.dateFormat(new Date()),
					orderTime:this.utils.dateFormat(new Date()),
					orderStatus:2,//平台派单状态
					orderReceivingStatus:0,//技师接单状态设置为 未接单1.
					type:1,
					payStatus:1,
					incPrice:0,
					storeOrTechnicianName:this.userInfo.name,
					technicianAge:this.userInfo.age,
					technicianId:this.userInfo.id,
					technicianLevel:this.userInfo.level,
					technicianLevelId:this.userInfo.levelId,
					technicianName:this.userInfo.name,
					technicianPhone:this.userInfo.mobile,
					storeName:this.userInfo.storeName,
					storeId:this.userInfo.storeId,
					adminOrderType:5,
					projectId:this.ederly.projectId
				};
				
				console.log("提交信息",orde)
				this.request.postRequest(this.http.httpsLian.technicianCreateElderly,orde)
				.then(res => { 
					 if(res.code==0){
						console.log("预约单提交返回:"+JSON.stringify(res))
					    uni.showToast({
					    	title:'确认服务成功',
					    	icon:"success",
					    	duration: 1800
					    })
						this.showService=false;
						//页面跳转
						setTimeout(()=>{
							uni.navigateTo({
							   url: "/pagesB/index/dispatch",
							});
						}, 1700)
						/* uni.switchTab({
						      url: '/pages/user/user' // 注意这里的路径应该与pages.json中定义的pagePath一致
						    }); */
							
					} else{
						uni.showToast({
							title:'确认服务失败',
							icon:"error",
							duration: 1800
						})
					}
					
				}).catch(res => {
					uni.$u.toast("预约单失败，请使用后台重新派单")
				})
			},
			//点击服务
			clickService(itme){
				this.from.serveName="请选择服务"
				this.showService=true;
				this.datalist=[]
				console.log("点击老人服务",itme)
				this.ederly=itme;
				let list =JSON.parse(itme.homemakingName)
				list.forEach((item,index)=>{
					console.log("选择服务",item)
					this.datalist.push({
						label:item.name,
						value:item.id,
						id:item.id,
						name:item.name,
						price:item.price,
						unit:item.unit,
					})
				})
				//this.showSearchPicker=true 
			
			},
			//选择服务
			onConfirm(val){
				console.log("this.datalist",this.datalist)
				console.log("选择服务",val[0].val)
				let da=this.datalist.find(item=>item.id==val[0].val)
				console.log("选择服务da",da)
				
				this.from.serveName=da.name
				this.from.price=da.price
				this.from.unit=da.unit
				this.from.id=da.id
			},
			open() {
			  console.log('open');
			},
			close() {
			  this.showService = false
			   console.log('close');
			},
			//唤醒手机拨号
			getPhoneNumber(user_phone){
				uni.makePhoneCall({
				 	phoneNumber:user_phone,
				 	 success(res) {
				 	 	console.log(res,'拨打成功')
				 	 }
				})
			},
			//页面跳转方法8
			navigateToAuditCompletedOrde(itme) {
				uni.navigateTo({
				   url: "./AuditCompletedOrde?params="+encodeURIComponent(JSON.stringify(itme))
				});
				
			},
			reset(){
				this.form = {
				  serveName: "",
				  price: "",
				  unit: "",
				  id: "",
				 
				};
			},
			//上拉事件触发
			onReachBottomZ(){
				console.log('上拉事件触发');
				this.pageVO.pageNo+=1
				this.status = 'loading';
				this.showPage(true)
				this.$emit('onReachBottomZ')
			},
			// 页面下拉时触发，与 onLoad 等生命周期函数平级
			onPullDownRefreshZ() {
				console.log('页面下拉时触发');
				this.status = 'loadmore';
				//回复默认值
				this.list=[]
				this.pageVO.pageNo=1
				this.pageVO.pageSize=4
				this.showPage(true)
			    setTimeout(() => {
					// 操作完成时，必须结束下拉刷新，否则一直会有 loading 标志
					uni.stopPullDownRefresh();
				}, 1000);
			},
			calculateAgeAndGender(idCard,type) {
			    if (!idCard || idCard.length !== 18) {
			        return'无';
			    }
			    let age=0
			    let birthYear = idCard.substr(6, 4);
			    let birthMonth = idCard.substr(10, 2);
			    let birthDay = idCard.substr(12, 2);
			    let genderCode = parseInt(idCard.substr(16, 1), 10);
			    let gender = genderCode % 2 === 0 ? '女' : '男';
			    let birthDate = new Date(`${birthYear}-${birthMonth}-${birthDay}`);
			    let now = new Date();
			     age = now.getFullYear() - birthYear;
			    const m = now.getMonth() - birthMonth;
			    if (m < 0 || (m === 0 && now.getDate() < birthDay)) {
			        age--;
			    }
				if(type=="age"){
					return age ;
				}
				if(type=="sex"){
					return  gender ;
				}
			   
			}
		}
	}
</script>

<style lang="scss" scoped>
	image,.xinxi{
		 width: 100%;
		 height: 300rpx;
	}
	.box{
		//margin: 5px;
		margin:0px 10px;
		background-color: white;
		padding: 8px ;
		//margin-top: 10px;
		margin-bottom: 10px;
		border-radius: 4px;
		//font-size: 42rpx;
	}
	.xinxi{
		margin-left: 5px;
		line-height: 60rpx;
		//font-size: 42rpx;
	}
	.address{
		//font-size: 42rpx;
		margin-bottom: 20rpx;
	}
	.service{
		width:500rpx;
		padding: 20rpx;
		border-radius: 10px;
		margin-top: 50rpx;
	}
	.buttonSER{
		margin-top: 50rpx;
	}
</style>
